package com.liuxingzhiwu.ruijishangcheng.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.liuxingzhiwu.ruijishangcheng.common.R;
import com.liuxingzhiwu.ruijishangcheng.entity.User;
import com.liuxingzhiwu.ruijishangcheng.service.UserService;
import com.liuxingzhiwu.ruijishangcheng.utils.MailUtils;
import com.liuxingzhiwu.ruijishangcheng.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMassage(@RequestBody User user, HttpSession session){

        String phone = user.getPhone();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        //严重是否有此手机号
        Long count = userService.count(queryWrapper);

        if(StringUtils.isNotEmpty(phone)&&count==1L){
            //生成6位验证码
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            session.setAttribute("code",code);
            log.info("验证码 = = "+code);
            MailUtils.sendMail("3278437553@qq.com","你好，瑞吉外卖注册验证码："+code,"验证码");
            return R.success("发送验证码成功");
        }
        return  R.error("手机号错误");

    }

    /**
     * d登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){

        String phone = (String) map.get("phone");
        String code = (String) map.get("code");
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",phone);
        //验证手机号是否错误
        Long count = userService.count(queryWrapper);
        if(StringUtils.isNotEmpty(phone)&&count == 1L &&(session.getAttribute("code").equals(code))){
            User user = userService.getOne(queryWrapper);
            session.setAttribute("user",user.getId());
            return R.success(user);
        }
        return R.error("登录失败");
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @PostMapping("/loginout")
    private R<String> loginOut(HttpServletRequest request){
        //清理Session中保存的当前员工的id
        request.getSession().removeAttribute("user");
        return R.success("已退出登录");
    }

}
